package com.seleniti.enpareja.android.control.entrypoint;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.ioc.commons.flowcontrol.common.impl.ReceiverAdapter;
import org.ioc.commons.flowcontrol.exceptionparser.ExceptionParserManager.ExceptionParser;
import org.ioc.commons.impl.android.flowcontrol.logincontroller.LoginControllerService;
import org.ioc.commons.impl.android.utils.log.AndroidFormatterLogger;
import org.ioc.commons.utils.FormatterLogger;

import android.app.Application;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.preference.PreferenceManager;
import android.util.Log;

import com.seleniti.enpareja.android.control.controller.EnParejaExceptionControllerImpl;
import com.seleniti.enpareja.android.control.factory.ClientFactoryImpl;
import com.seleniti.enpareja.controller.common.exception.EnParejaException;
import com.seleniti.enpareja.controller.ui.base.EnParejaBasePresenter;

public class EnParejaAndroid extends Application implements ExceptionParser<EnParejaException> {

	private ClientFactoryImpl clientFactory;

	@Override
	public void onCreate() {
		super.onCreate();

		FormatterLogger.setImplementation(AndroidFormatterLogger.implementator());

		setWebSiteUrl();

		this.clientFactory = new ClientFactoryImpl(this);

		EnParejaBasePresenter.setClientFactory(clientFactory);
		LoginControllerService.setAuthenticatorProvider(clientFactory.getAuthenticatorProvider());
		// WebViewActivity.setPlaceControllerProvider(clientFactory.getPlaceController());

		((EnParejaExceptionControllerImpl) clientFactory.getExceptionController())
				.setAsDefaultUncaughtExceptionHandler();
		ReceiverAdapter.setGlobalExceptionController(clientFactory.getExceptionController());

		/**
		 * Registering exception parser
		 */
		clientFactory.getExceptionController().registerExceptionParser(EnParejaException.class, this);

	}

	public void setWebSiteUrl() {
		Resources resources = this.getResources();
		AssetManager assetManager = resources.getAssets();

		// Read from the /assets directory
		Properties properties = new Properties();
		try {
			InputStream inputStream = assetManager.open("config.properties");
			properties.load(inputStream);
			System.out.println("The properties are now loaded");
			System.out.println("properties: " + properties);

			SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
			boolean isDebug = sharedPref.getBoolean("isDebug", false);

			String url = !isDebug ? properties.getProperty("website.url") : properties.getProperty("dev.website.url");
			ClientFactoryImpl.setWebsiteUrl(url);

		} catch (IOException e) {
			System.err.println("Failed to open config property file");
			e.printStackTrace();
			throw new RuntimeException("Failed to open config property file", e);
		}
	}

	public ClientFactoryImpl getClientFactory() {
		return clientFactory;
	}

	@Override
	public EnParejaException fromMessage(String message) {
		return EnParejaException.fromMessage(message);
	}

	@Override
	public boolean tryHandleException(Throwable e) {
		return false;
	}

	//TODO: Probar a llamar esto
	public void clearApplicationData() {
		File cache = getCacheDir();
		File appDir = new File(cache.getParent());
		if (appDir.exists()) {
			String[] children = appDir.list();
			for (String s : children) {
				if (!s.equals("lib")) {
					deleteDir(new File(appDir, s));
					Log.i("TAG", "File /data/data/APP_PACKAGE/" + s + " DELETED");
				}
			}
		}
	}

	public static boolean deleteDir(File dir) {
		if (dir != null && dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}

		return dir.delete();
	}
}
